<template>
  <div class="marketing-report">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>营销报表</span>
          <div class="header-actions">
            <el-select v-model="chartType" placeholder="选择图表类型" size="small" @change="handleChartTypeChange">
              <el-option label="柱状图" value="bar" />
              <el-option label="饼图" value="pie" />
              <el-option label="折线图" value="line" />
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="exportReport" size="small">导出报表</el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">总销量</div>
              <div class="stat-value">{{ statistics.totalSales }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">最受欢迎类型</div>
              <div class="stat-value">{{ statistics.popularType }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">增长率最高</div>
              <div class="stat-value">{{ statistics.fastestGrowth }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">平均增长率</div>
              <div class="stat-value">{{ statistics.avgGrowthRate }}%</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="chartType === 'pie' ? 12 : 24">
          <el-card class="chart-card">
            <template #header>
              <span>鞋子类型销量统计</span>
            </template>
            <div ref="typeChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12" v-if="chartType === 'pie'">
          <el-card class="chart-card">
            <template #header>
              <span>销量占比详情</span>
            </template>
            <div class="pie-legend">
              <div v-for="item in typeSalesData" :key="item.type" class="legend-item">
                <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
                <span class="legend-text">{{ item.type }}</span>
                <span class="legend-value">{{ item.sales }}双</span>
                <span class="legend-percent">{{ item.percent }}%</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card class="detail-card">
        <template #header>
          <span>类型销售详情</span>
        </template>
        <el-table :data="typeSalesData" style="width: 100%" v-loading="loading">
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column prop="type" label="鞋子类型" />
          <el-table-column prop="sales" label="销量（双）" width="120" sortable />
          <el-table-column prop="growthRate" label="增长率" width="120" sortable>
            <template #default="{ row }">
              <span :class="row.growthRate >= 0 ? 'growth-positive' : 'growth-negative'">
                {{ row.growthRate >= 0 ? '+' : '' }}{{ row.growthRate }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="lastMonthSales" label="上月销量" width="120" />
          <el-table-column prop="monthlyTarget" label="月度目标" width="120" />
          <el-table-column prop="completionRate" label="完成率" width="120">
            <template #default="{ row }">
              <el-progress 
                :percentage="row.completionRate" 
                :status="row.completionRate >= 100 ? 'success' : row.completionRate >= 80 ? 'warning' : 'exception'"
              />
            </template>
          </el-table-column>
          <el-table-column prop="revenue" label="销售额" width="120" sortable>
            <template #default="{ row }">
              ¥{{ row.revenue }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getMarketingReport, exportMarketingReport } from '../api/report.js'

// 数据
const loading = ref(false)
const chartType = ref('bar')
const dateRange = ref([])
const typeChart = ref(null)
let typeChartInstance = null

// 统计数据
const statistics = reactive({
  totalSales: 2345,
  popularType: '运动鞋',
  fastestGrowth: '凉鞋',
  avgGrowthRate: 15.6
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 类型销售数据
const typeSalesData = ref([])

// 模拟数据
const mockTypeSalesData = [
  {
    rank: 1,
    type: '运动鞋',
    sales: 856,
    growthRate: 12.5,
    lastMonthSales: 761,
    monthlyTarget: 800,
    completionRate: 107,
    revenue: '428,000',
    color: '#5470c6'
  },
  {
    rank: 2,
    type: '休闲鞋',
    sales: 623,
    growthRate: 8.3,
    lastMonthSales: 575,
    monthlyTarget: 600,
    completionRate: 103.8,
    revenue: '311,500',
    color: '#91cc75'
  },
  {
    rank: 3,
    type: '皮鞋',
    sales: 445,
    growthRate: -2.1,
    lastMonthSales: 455,
    monthlyTarget: 500,
    completionRate: 89,
    revenue: '445,000',
    color: '#fac858'
  },
  {
    rank: 4,
    type: '凉鞋',
    sales: 312,
    growthRate: 25.6,
    lastMonthSales: 248,
    monthlyTarget: 300,
    completionRate: 104,
    revenue: '156,000',
    color: '#ee6666'
  },
  {
    rank: 5,
    type: '靴子',
    sales: 109,
    growthRate: -8.4,
    lastMonthSales: 119,
    monthlyTarget: 150,
    completionRate: 72.7,
    revenue: '130,800',
    color: '#73c0de'
  }
]

// 初始化类型销量图表
const initTypeChart = () => {
  if (typeChartInstance) {
    typeChartInstance.dispose()
  }
  
  typeChartInstance = echarts.init(typeChart.value)
  
  let option = {}
  
  if (chartType.value === 'bar') {
    option = {
      title: {
        text: '各类型鞋子销量对比',
        subtext: '单位：双',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: typeSalesData.value.map(item => item.type),
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '销量（双）'
      },
      series: [
        {
          name: '销量',
          type: 'bar',
          data: typeSalesData.value.map(item => item.sales),
          itemStyle: {
            color: function(params) {
              return typeSalesData.value[params.dataIndex].color
            }
          },
          label: {
            show: true,
            position: 'top'
          }
        }
      ]
    }
  } else if (chartType.value === 'pie') {
    const total = typeSalesData.value.reduce((sum, item) => sum + item.sales, 0)
    const pieData = typeSalesData.value.map(item => ({
      name: item.type,
      value: item.sales,
      percent: ((item.sales / total) * 100).toFixed(1)
    }))
    
    // 更新数据的百分比
    typeSalesData.value.forEach((item, index) => {
      item.percent = pieData[index].percent
    })
    
    option = {
      title: {
        text: '各类型销量占比',
        subtext: '总计：' + total + '双',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}双 ({d}%)'
      },
      legend: {
        show: false
      },
      series: [
        {
          name: '销量占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}\n{c}双\n({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: pieData
        }
      ]
    }
  } else if (chartType.value === 'line') {
    option = {
      title: {
        text: '各类型销量趋势',
        subtext: '月度对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: typeSalesData.value.map(item => item.type),
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['第1周', '第2周', '第3周', '第4周']
      },
      yAxis: {
        type: 'value',
        name: '销量（双）'
      },
      series: typeSalesData.value.map(item => ({
        name: item.type,
        type: 'line',
        smooth: true,
        data: [
          Math.floor(item.sales * 0.2),
          Math.floor(item.sales * 0.25),
          Math.floor(item.sales * 0.3),
          Math.floor(item.sales * 0.25)
        ],
        lineStyle: {
          color: item.color,
          width: 2
        },
        itemStyle: {
          color: item.color
        }
      }))
    }
  }
  
  typeChartInstance.setOption(option)
}

// 方法
const getReportData = async () => {
  try {
    loading.value = true
    const response = await getMarketingReport({
      page: currentPage.value,
      pageSize: pageSize.value,
      dateRange: dateRange.value,
      chartType: currentChartType.value
    })
    
    if (response.success) {
      typeSalesData.value = response.data.list || response.data || []
      total.value = response.data.total || response.total || typeSalesData.value.length
      
      // 更新统计数据
      if (response.data.statistics) {
        Object.assign(statistics, response.data.statistics)
      }
    } else {
      ElMessage.error(response.message || '获取营销报告失败')
      // 回退到模拟数据
      typeSalesData.value = mockTypeSalesData
      total.value = mockTypeSalesData.length
    }
  } catch (error) {
    console.error('获取营销报告失败:', error)
    ElMessage.error('获取营销报告失败，请稍后重试')
    // 回退到模拟数据
    typeSalesData.value = mockTypeSalesData
    total.value = mockTypeSalesData.length
  } finally {
    loading.value = false
  }
}

const handleChartTypeChange = () => {
  initTypeChart()
}

const handleDateChange = () => {
  getReportData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const exportReport = async () => {
  try {
    const response = await exportMarketingReport({
      dateRange: dateRange.value,
      chartType: currentChartType.value
    })
    
    if (response) {
      // 创建下载链接
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `营销报告_${new Date().toISOString().split('T')[0]}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('报表导出成功')
    }
  } catch (error) {
    console.error('导出营销报告失败:', error)
    ElMessage.error('导出营销报告失败，请稍后重试')
  }
}

// 响应式处理
const handleResize = () => {
  if (typeChartInstance) {
    typeChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  getReportData()
  setTimeout(() => {
    initTypeChart()
  }, 100)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (typeChartInstance) {
    typeChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.marketing-report {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 500px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.pie-legend {
  padding: 20px;
  height: 400px;
  overflow-y: auto;
}

.legend-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  margin-right: 10px;
}

.legend-text {
  flex: 1;
  font-weight: 500;
}

.legend-value {
  margin-right: 15px;
  color: #666;
}

.legend-percent {
  font-weight: bold;
  color: #303133;
}

.detail-card {
  margin-bottom: 20px;
}

.growth-positive {
  color: #67c23a;
  font-weight: bold;
}

.growth-negative {
  color: #f56c6c;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>